package com.hjy.controller;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "ImageController", value = "/image")
public class ImageController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Refresh","3");
        //创建一张图片进内存,该图片有80px宽,20px高,类型是具有整数像素的 8 位 RGB 颜色
        BufferedImage image = new BufferedImage(150,100,BufferedImage.TYPE_INT_RGB);
        Graphics2D pen = (Graphics2D) image.getGraphics();
        //设置画笔的颜色
        pen.setColor(Color.white);
        //填充这块区域
        pen.fillRect(0,0,150,100);
        pen.setColor(Color.blue);
        //设置字体
        pen.setFont(new Font(null,Font.BOLD,20));
        //写入字符串,x轴从左往右,y轴从上往下
        pen.drawString(getCode(),0,50);
        //设置该请求以图片的形式打开
        response.setContentType("image/jpeg");
        //设置无缓存
        response.setHeader("Cache-Control","nocache");
        response.setHeader("Pragma","no-cache");
        //这个和setHeader一样,只是值只可以为long类型而不是字符串了
        response.setDateHeader("Expires",-1);
        //把图片给浏览器
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
    //获取随机验证码
    public String getCode(){
        String s = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        String returnValue = "";
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            //取码是[0,len)
            int i1 = random.nextInt(s.length());
            returnValue+=s.charAt(i1);
        }
        return returnValue;
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
